import {
	client
} from "../../utils/request.js"
import {
	throttle
} from "../../utils/tools";

const DEFAULT_PAGE = 0;
Page({
	startPageX: 0,
	currentView: DEFAULT_PAGE,
	onShareAppMessage() {
		return {
			title: 'movable-view',
			path: 'page/component/pages/movable-view/movable-view'
		}
	},

	data: {
		toView: `card_${DEFAULT_PAGE}`,
		list: [],
		animationData: '',
		movableViewDisabled: false,
		username: 'Cowjiang',
		studentId: 1940706103,
		score: 4983,
		areaHeight: null,
		topHeight: null,
		centerHeight: null,
		copyrightHeight: null,
		movableViewHeight: null, // movable-view 计算后的高度
		integral: "", //积分
		address: "",
		isList:false
	},
	/**
	 * movable-view 滑动监听事件
	 */
	onChange(e) {
		let outsideY = e.detail.y
		let animation = wx.createAnimation({ // 背景图片动效
			duration: 275,
			timingFunction: 'linear'
		})
		let rpx = 195;
		let systemInfo = wx.getSystemInfoSync();
		let px = rpx / 750 * systemInfo.windowWidth
		if (e.detail.source === "touch-out-of-bounds" && Math.sqrt(outsideY) / 3.8 >= 1) { // 二段动效
			animation.scale(Math.sqrt(outsideY) / 3.8).translateY(Math.sqrt(outsideY) * 5 - px).step()
		} else if (e.detail.source === "touch-out-of-bounds" && Math.sqrt(outsideY) / 3.8 < 1) { // 初段动效
			animation.translateY(Math.sqrt(outsideY) * 5 - px).step()
		} else if (e.detail.source !== "touch-out-of-bounds" && Math.sqrt(outsideY) > 0) { // 未超出 movable-view 区域时的动效
			animation.scale(1).translateY(-px).step()
		}
		this.setData({
			animationData: animation.export()
		})
	},

	onLoad() {
		// 获取 movable-area 容器高度
		let movableAreaHeightQuery = wx.createSelectorQuery()
		// 获取 movable-view 内容高度
		let topHeightQuery = wx.createSelectorQuery()
		let centerHeightQuery = wx.createSelectorQuery()
		let copyrightHeightQuery = wx.createSelectorQuery()
		movableAreaHeightQuery.select('.movable-frame').boundingClientRect(rect => {
			this.setData({
				areaHeight: rect.height
			})
		}).exec();
		topHeightQuery.select('.top').boundingClientRect(rect => {
			this.setData({
				topHeight: rect.height
			})
		}).exec();
		centerHeightQuery.select('.center').boundingClientRect(rect => {
			this.setData({
				centerHeight: rect.height
			})
		}).exec();
		copyrightHeightQuery.select('.copyright').boundingClientRect(rect => {
			this.setData({
				copyrightHeight: rect.height
			})
		}).exec();

		// 计算movable-view内容高度
		var heightQuery = setInterval(() => {
			if (this.data.topHeight !== null && this.data.centerHeight !== null && this.data.copyrightHeight !== null) {
				// 仅对movable-area高度小于movable-view内容高度时，动态调整movable-view的高度
				if (this.data.areaHeight < this.data.topHeight + this.data.centerHeight + this.data.copyrightHeight) {
					this.setData({
						movableViewHeight: (this.data.topHeight + this.data.centerHeight + this.data.copyrightHeight + 25)
					})
				}
				clearInterval(heightQuery)
			}
		}, 10)
	},

	returnIndex() {
		wx.reLaunch({
			url: '../index/index'
		})
	},
	onShow() {
		let that = this
		wx.getStorage({
			key: 'userInfo',
			success(res) {
				that.setData({
					userInfo: res.data
				})
			}
		})
		that.initScore()

		that.init()

	},
	/**
	 * 每日签到
	 */
	signIn() {
		let that = this
		wx.showLoading({
			title: '加载中',
			success() {
				let address = that.data.address
				client({
					url: 'users/dailySignIn',
					method: "post",
					data: {
						address
					}
				}).then(data => {
					wx.showToast({
						title: data.data.msg,
						icon: 'success',
						duration: 2000
					})
					that.initScore()
				}).catch(err => {
					console.log(err)
				})
				setTimeout(function () {
					wx.hideLoading()
				}, 100)
				that.setData({
					isSingnIn: true
				})
			}
		})

	},

	initScore() {
		// 积分接口
		let that = this
		wx.getStorage({
			key: 'userInfo',
			success(res) {
				let address = res.data.address
				client({
					url: 'users/getBalances?address=' + address
				}).then(data => {

					let integral = data.data.value
					that.setData({
						integral: integral,
						address: address
					})
				}).catch(err => {
					console.log(err)
				})
			}
		})

	},

	/**
	 * 联系我们
	 */
	toAboutUs: throttle(function (e) {
		//跳转到选择页面
		wx.reLaunch({
			url: '../aboutUs/aboutUs',
		})
	}, 200),

	/*
	 * 预约记录
	 * */
	init: function () {
		let that = this
		let url = 'http://agitator.cn.utools.club/'
		wx.getStorage({
			key: 'userInfo',
			success(res) {
				let username = res.data.username
				let schoolName = 'HR'
				wx.request({
					url: url + 'seatInfo/getMySeatHistory',
					data: {
						username,
						schoolName
					},
					method: "POST",
					success: function (res) {
						let array = res.data.data;
						let arr = array.reverse()
						let arrObj = arr.map(function (item, index, arr) {
							let id = item.seatId
							let roomName = item.seat_info[0].roomName
							let roomDome = item.seat_info[0].room
							let floor = roomDome.slice(0, 2);
							let room = roomDome.slice(3, 5)
							let date = item.createdTime.substring(5, 10);
							let time = item.timeSlotArr[0] + ":00-" + item.timeSlotArr[item.timeSlotArr.length - 1] + ":00"
							let arrObj = {
								date,
								room,
								id,
								time,
								roomName,
								floor
							}
							return arrObj
						})
						let len = arrObj.length;
						let n = 4; //假设每行显示4个
						let lineNum = len % 4 === 0 ? len / 4 : Math.floor((len / 4) + 1);
						let dataArr = [];
						for (let i = 0; i < lineNum; i++) {
							let temp = arrObj.slice(i * n, i * n + n);
							dataArr.push(temp);
						}
						that.setData({
							list: dataArr,
							isList:true
						})
					}
				})
			}
		})
	},

	/*
	 * 预约记录的滑动
	 * */
	touchStart(e) {
		this.startPageX = e.changedTouches[0].pageX;
	},
	touchEnd(e) {
		const moveX = e.changedTouches[0].pageX - this.startPageX;
		const maxPage = this.data.list.length - 1;
		if (Math.abs(moveX) >= 150) {
			if (moveX > 0) {
				this.currentView = this.currentView !== 0 ? this.currentView - 1 : 0;
			} else {
				this.currentView = this.currentView !== maxPage ? this.currentView + 1 : maxPage;
			}
		}
		this.setData({
			toView: `card_${this.currentView}`
		});
	}
})